package org.txazo.stat.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.txazo.stat.dao.UserDao;
import org.txazo.stat.vo.User;

/**
 * 用户数据访问实现
 * 
 * @author Tu XiaoZhou
 * @since 2013-04-12
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return namedParameterJdbcTemplate;
	}

	public void setNamedParameterJdbcTemplate(
			NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
	}

	@Override
	public boolean isAccountExist(String account) {
		String sql = "select count(1) from user where account = ?";
		return namedParameterJdbcTemplate.getJdbcOperations().queryForObject(
				sql, Integer.class, account) == 1;
	}

	@Override
	public User login(String account, String password) {
		User user = null;
		String sql = "select * from user where account = ? and password = ?";
		try {
			user = namedParameterJdbcTemplate.getJdbcOperations()
					.queryForObject(
							sql,
							ParameterizedBeanPropertyRowMapper
									.newInstance(User.class),
							new Object[] { account, password });
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
		return user;
	}

	@Override
	public void register(User user) {
		String sql = "insert into user (account, password, nickname, regTime) values (?, ?, ?, ?)";
		namedParameterJdbcTemplate.getJdbcOperations().update(
				sql,
				new Object[] { user.getAccount(), user.getPassword(),
						user.getNickname(), user.getRegTime() });
	}

	@Override
	public void updatePassword(int id, String password) {
		String sql = "update user set password = ? where id = ?";
		namedParameterJdbcTemplate.getJdbcOperations().update(sql,
				new Object[] { password, id });
	}

}
